//
//  BHMyFunDetailViewController.swift
//  BigHealth
//
//  Created by 蔺百好 on 2021/6/30.
//

import UIKit

class BHMyFunDetailViewController: BHBaseViewController {
    
    var refreshFunListBlock:(() -> Void)?
    

    lazy var tableView: UITableView = {
        let view = UITableView.buildTableView(style: .grouped)
        view.frame = CGRect(x: 0, y: UIScreen.begainY, width: UIScreen.width, height: UIScreen.showHeight)
        view.delegate = self
        view.dataSource = self
        return view
    }()
    
    lazy var serviceManager: BHMeUserFunServiceManager = {
        let manager = BHMeUserFunServiceManager.init()
        return manager
    }()
    
    // 0参加别人的活动   1自己创建的活动
    var funApplyType: Int = 0
    var funId: String = "" // 趣玩id
    
    fileprivate var detailModel = BHUserFunApplyDetailModel.init()
    
    override func viewDidLoad() {
        super.viewDidLoad()

        self.regiseterCell()
        self.bh_navigationBar.title_label.text = "详情"
        self.view.addSubview(self.tableView)
        
        self.bh_navigationBar.rightBtn.isHidden = false
        self.bh_navigationBar.rightBtn.titleLabel?.font = .systemFont(ofSize: 12, weight: .medium)
        self.bh_navigationBar.rightBtn.setTitleColor(.color_D43939, for: .normal)
        if self.funApplyType == 1 {
            self.bh_navigationBar.rightBtn.setTitle("解散群聊", for: .normal)
        }else {
            self.bh_navigationBar.rightBtn.setTitle("退出趣玩", for: .normal)
        }
        
        self.serviceManager.funId = self.funId
        self.responseForNet()
        SVProgressHUD.show()
        self.serviceManager.queryApplyDetailService()
    }
    
    override func rightBtnAction() {
        
        
        BHCommonTool.showAlertWith(showVC: self, title: "提示", message: self.funApplyType == 1 ? "是否确定解散趣玩？":"是否确认退出趣玩？", okBtn: "确认", cancel: "取消") { (confirm) in
            if confirm {
                if self.funApplyType == 1 { // 自己创建的，解散
                    SVProgressHUD.show()
                    self.serviceManager.createrDissolveFunService()
                }else { // 他人创建的，退出
                    SVProgressHUD.show()
                    self.serviceManager.userQuiteService(signupId: self.detailModel.signupId)
                }
            }
        }

    }

    
}
extension BHMyFunDetailViewController {
    private func regiseterCell() {
        
        
        self.tableView.regiseterNib(nibName: "BHFunDetailTeamSecCell")
        self.tableView.regiseterNib(nibName: "BHFunDetailTeamUserCell")
        self.tableView.regiseterNib(nibName: "BHFunDetailSelfApplyInfoCell")
        self.tableView.regiseterNib(nibName: "BHMyFunDetailInfoCell")
        self.tableView.regiseterNib(nibName: "BHApplyDetailInfoCell")
        self.tableView.regiseterNib(nibName: "BHApplyStepTableViewCell")
        self.tableView.regiseterNib(nibName: "BHApplyOrderInfoCell")
    }
}

extension BHMyFunDetailViewController: UITableViewDataSource {
    func numberOfSections(in tableView: UITableView) -> Int {
        if self.funApplyType == 1 { // 自己创建的活动没有订单信息
            return 3
        }
        return 4
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if section == 1 {
            if self.funApplyType == 0 {
                return 1
            }else {
                return self.detailModel.signUserArray.count+1
            }
        }else if section == 2{
            return 3
        }else {
            return 1
        }
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        if section != 0 {
            return 10
        }
        return 10
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return CGFloat.leastNormalMagnitude
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if indexPath.section == 0 {
            return BHMyFunDetailInfoCell.funHeight
        }else if indexPath.section == 1 {
            if self.funApplyType == 0 {
                return BHFunDetailSelfApplyInfoCell.infoHeight
            }else {
                if indexPath.row == 0 {
                    return 37
                }
                return 54
            }
        }else if indexPath.section == 2 {
            return 80
        }else {
            return 120
        }
    }
    
    func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
        if self.funApplyType == 1 {
            if indexPath.section == 0 {
                return true
            }else if indexPath.section == 1 {
                if indexPath.row != 0 {
                    return true
                }else {
                    return false
                }
            }else {
                return false
            }
        }else {
            return false
        }
    }
    
    
    func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
        if indexPath.section == 0 {
            let action = UITableViewRowAction.init(style: .destructive, title: "编辑") { (act, index) in
                if self.detailModel.signUserArray.count != 0 {
                    BHToast.toast(text: "当前活动已有组员，无法编辑")
                    return
                }
                
                let editeVC = BHFunAddFunnyViewController.init()
                editeVC.type = 1
                editeVC.funId = self.funId
                self.navigationController?.pushViewController(editeVC, animated: true)
                editeVC.completeRefreshBlock = { [weak self] in
                    self?.serviceManager.queryApplyDetailService()
                }
            }
            
            return [action]
        }else {
            let action = UITableViewRowAction.init(style: .default, title: "移除") { (act, index) in
                let model = self.detailModel.signUserArray[indexPath.row-1]

                BHCommonTool.showAlertWith(showVC: nil, title: "提示", message: "是否移除\(model.signName)", okBtn: "确定", cancel: "再想想") { (confirm) in
                    if confirm == true {
                        SVProgressHUD.show()
                        self.serviceManager.createrRemoveUserService(userId: model.userId)
                    }
                }
            }
            
            return [action]
        }
        
    }
    
}

extension BHMyFunDetailViewController {
    func editeApplyInfoAct() {
        let editeVC: BHApplyUserInfoEditeViewController = BHApplyUserInfoEditeViewController.init()
        editeVC.editeType = 1
        editeVC.applyFunDetailModel = self.detailModel
        self.navigationController?.pushViewController(editeVC, animated: true)
        editeVC.refreshDetailInfoBlock = { [weak self] in
            SVProgressHUD.show()
            self?.serviceManager.queryApplyDetailService()
        }
    }
}

extension BHMyFunDetailViewController: UITableViewDelegate {
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        if section != 0 {
            let view = UIView.init(frame: CGRect(x: 0, y: 0, width: UIScreen.width, height: 10))
            view.backgroundColor = .color_f8f8f8
            return view
        }
        return nil
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if indexPath.section == 0 {
            return cellForFunInfo(indexPath: indexPath)
        }else if indexPath.section == 1 {
            if self.funApplyType == 0 {
                return cellForSelfApply(indexPath: indexPath)
            }else {
                if indexPath.row == 0 {
                    return cellForTeamSec(indexPath: indexPath)
                }else {
                    return cellForTeamUser(indexPath: indexPath)
                }
            }
        }else if indexPath.section == 2 {
            return cellForStep(indexPath: indexPath)
        }else if indexPath.section == 3 {
            return cellForOrderInfo(indexPath: indexPath)
        }
        
        return UITableViewCell()
    }
}


extension BHMyFunDetailViewController {
    func cellForFunInfo(indexPath: IndexPath) -> UITableViewCell {
        let cell = self.tableView.dequeueReusableCell(withIdentifier: "BHMyFunDetailInfoCell", for: indexPath) as! BHMyFunDetailInfoCell
        cell.model = self.detailModel
        return cell
    }
    
    func cellForSelfApply(indexPath: IndexPath) -> UITableViewCell {
        let cell = self.tableView.dequeueReusableCell(withIdentifier: "BHFunDetailSelfApplyInfoCell", for: indexPath) as! BHFunDetailSelfApplyInfoCell
        cell.model = self.detailModel
        cell.editeBtn.addBtnAction(action: {[weak self] (_) in
            self?.editeApplyInfoAct()
        }, for: .touchUpInside)
        cell.phoneBtn.addBtnAction(action: {[weak self] (_) in
            if self?.detailModel.signUserPhone == nil {
                return
            }
            BHCommonTool.telAct(self?.detailModel.signUserPhone ?? "") { (canTel) in
                
            }
        }, for: .touchUpInside)
        
        return cell
    }
    
    func cellForStep(indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "BHApplyStepTableViewCell", for: indexPath) as! BHApplyStepTableViewCell
        if indexPath.row == 0 {
            cell.name_label.text = "报名活动"
            cell.time_label.text = "\(self.detailModel.signupTime)"
            cell.upline.isHidden = true
            cell.downline.isHidden = false
        }else if indexPath.row == 1 {
            cell.name_label.text = "报名截止"
            cell.time_label.text = "\(self.detailModel.signupEndTime)"
            cell.upline.isHidden = false
            cell.downline.isHidden = false
        }else {
            cell.name_label.text = "活动开始"
            cell.time_label.text = "\(self.detailModel.beginTime)"
            cell.upline.isHidden = false
            cell.downline.isHidden = true
        }
        return cell
    }
    
    func cellForOrderInfo(indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "BHApplyOrderInfoCell", for: indexPath) as! BHApplyOrderInfoCell
        cell.order_label.text = "订单编号：\(self.detailModel.orderCode)"
        cell.pay_time_label.text = "支付时间：\(self.detailModel.payTime)"
        return cell
    }
    
    func cellForTeamSec(indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "BHFunDetailTeamSecCell", for: indexPath) as! BHFunDetailTeamSecCell
        return cell
    }
    
    func cellForTeamUser(indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "BHFunDetailTeamUserCell", for: indexPath) as! BHFunDetailTeamUserCell
        let model = self.detailModel.signUserArray[indexPath.row-1]
        cell.model = model
        cell.phoneBtn.addBtnAction(action: { (_) in
            if model.signPhone.isEmpty == true {
                return
            }
            BHCommonTool.telAct(model.signPhone) { (canTel) in
                
            }
        }, for: .touchUpInside)
        return cell
    }
}

extension BHMyFunDetailViewController {
    func responseForNet()  {
        self.serviceManager.responseForMainDetailBlock = {[weak self] (success,errorMsg,model) in
            SVProgressHUD.dismiss()
            if success == true {
                self?.detailModel = model
                if model.launchUserId == BHMeUserInfoModel.shared.userId {
                    self?.funApplyType = 1
                }
                self?.tableView.reloadData()
            }else {
                BHToast.toast(text: errorMsg)
            }
        }
        /**
         0 修改信息
         1 退出趣玩
         2 移除报名用户
         3 解散趣玩
         */
        self.serviceManager.responseForCompleteHandlerBlock = {[weak self] (success,errorMsg,type) in
            SVProgressHUD.dismiss()
            if success == false {
                BHToast.toast(text: errorMsg)
                return
            }
            if type == 0 {
                self?.refreshFunListBlock?()
            }
            if type == 1 {
                self?.refreshFunListBlock?()
                BHToast.toast(text: "已退出当前活动")
                DispatchQueue.main.asyncAfter(deadline: .now()+1) {
                    self?.navigationController?.popViewController(animated: true)
                }
               
            }
            if type == 2 {
                self?.serviceManager.queryApplyDetailService()
            }
            if type == 3 {
                self?.refreshFunListBlock?()
                BHToast.toast(text: "当前活动已解散")
                DispatchQueue.main.asyncAfter(deadline: .now()+1) {
                    self?.navigationController?.popViewController(animated: true)
                }
                
            }
        }
    }
}
